package com.sgb.kjwl.view.widget.transport;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import androidx.core.util.Pair;

import com.bumptech.glide.Glide;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppOfferDetailPopLayoutBinding;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.OrderQuoteEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.LonLatUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderForCompanyActivity;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;

/**
 * Describe:报价单位-地图页面-报价详情弹窗(普通货源)
 * Author:  yangLei
 * Date:    2021/9/17
 */
public class OfferDetailPopWindow extends BasePopWindow implements View.OnClickListener {

    private OrderQuoteEntity offerEntity;
    private AppOfferDetailPopLayoutBinding mBinding;

    public OrderQuoteEntity getOfferEntity() {
        return offerEntity;
    }

    public void setOfferEntity(OrderQuoteEntity offerEntity) {
        this.offerEntity = offerEntity;
        loadingOfferInfo(offerEntity);
    }

    public OfferDetailPopWindow(Context context) {
        super(context, DIR_DOWN_UP);
    }

    @Override
    protected int popLayout() {
        return R.layout.app_offer_detail_pop_layout;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        mBinding = (AppOfferDetailPopLayoutBinding) holder.getmBinding();
        mBinding.setOnClick(this::onClick);
    }

    /**
     * 加载报价详情
     *
     * @param entity
     */
    private void loadingOfferInfo(OrderQuoteEntity entity) {
        if (!TextUtils.isEmpty(entity.getOfferType())) {
            //头像
            if (!TextUtils.isEmpty(entity.getLogo())) {
                Glide.with(mContext).load(entity.getLogo())
                        .placeholder(R.drawable.icon_default_profile_photo_round)
                        .into(mBinding.offerUserIcon);
            }

            //运费报价
            mBinding.offerPrice.setText(!TextUtils.isEmpty(entity.getAllFreight()) ? NumberUtil.trim0(entity.getAllFreight()) + "元" : "/");
            //距离
            double distance = 0.0d;
            if (!TextUtils.isEmpty(entity.getDistance())) {
                distance = Double.parseDouble(entity.getDistance());
            } else if (entity.getLongitude() != null && entity.getLongitude() > 0
                    && entity.getLatitude() != null && entity.getLatitude() > 0) {
                distance = LonLatUtils.getDistance(entity.getLongitude(), entity.getLatitude(),
                        NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "")),
                        NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, ""))
                );
            }
            if (distance <= 0) {
                mBinding.offerDistance.setText("/");
            } else {
                mBinding.offerDistance.setText(distance < 1 ? "1km以内" : StringUtil.formatUpDistance(String.valueOf(distance)) + "km");
            }

            //地址
            String address = "";
            //名字
            String title = "";
            mBinding.offerAddressHint.setText("车辆位置");
            if (!TextUtils.isEmpty(entity.getDetailAddress())) {
                address = entity.getDetailAddress();
            }

            StringBuilder carInfo = new StringBuilder();
            String carNum = "";
            if (!TextUtils.isEmpty(UserOperating.getInstance().getUserNo())
                    && !TextUtils.isEmpty(entity.getUserNo())
                    && UserOperating.getInstance().getUserNo().equals(entity.getUserNo())) {
                title = !TextUtils.isEmpty(entity.getName()) ? entity.getName() : "/";
                carNum = !TextUtils.isEmpty(entity.getCarNumber()) ? entity.getCarNumber() : "";
            } else {
                title = !TextUtils.isEmpty(entity.getName()) ? entity.getName().substring(0, 1) + "师傅" : "/";
                carNum = !TextUtils.isEmpty(entity.getCarNumber()) ? replaceString2Star(entity.getCarNumber(), 2, 0) : "";
            }

            carInfo.append(carNum + "(");
            if (!TextUtils.isEmpty(entity.getCarTypeName())) {
                carInfo.append(entity.getCarTypeName());
            }
            if (!TextUtils.isEmpty(entity.getCarLenName())) {
                carInfo.append("/车长" + entity.getCarLenName());
            }
            if (!TextUtils.isEmpty(entity.getHeightHurdle())) {
                carInfo.append("/栏高" + NumberUtil.trim0(entity.getHeightHurdle()) + "米");
            }
            if (!TextUtils.isEmpty(entity.getIsDump())) {
                carInfo.append("/"+entity.getIsDump());
            }
            carInfo.append(")");
            mBinding.offerCarInfo.setText(carInfo.toString());
            mBinding.offerCarInfoLayout.setVisibility(View.VISIBLE);

            mBinding.offerUserName.setText(title);
            mBinding.offerAddress.setText(!TextUtils.isEmpty(address) ? address : "/");

            //判断是否已生成订单
            if (!TextUtils.isEmpty(entity.getOfferStatus()) && entity.getOfferStatus().equals("2")) {
                //报价已被同意
                mBinding.offerInfoBottomBar.setVisibility(View.VISIBLE);
                mBinding.bottomPadding.setVisibility(View.GONE);
            } else {
                mBinding.offerInfoBottomBar.setVisibility(View.GONE);
                mBinding.bottomPadding.setVisibility(View.VISIBLE);
            }

            //信息费用
            if (!TextUtils.isEmpty(entity.getSourceMessagePrice())) {
                mBinding.messagePriceInfo.setText(NumberUtil.trim0(entity.getSourceMessagePrice()) + "元");
            }

            mBinding.lineView.setVisibility(View.GONE);
            mBinding.offerInfoBottomBar.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(entity.getIsSelfOffer()) && entity.getIsSelfOffer().equals("1")//是自己报的价才处理
                    && !TextUtils.isEmpty(entity.getOfferStatus())) {
                //1已报价  2待支付(已同意)  3已支付 4超时未支付 5已失效/货主未同意
                switch (entity.getOfferStatus()) {
                    case "2":
                        mBinding.messagePriceHint.setText("待支付信息费");
                        mBinding.lineView.setVisibility(View.VISIBLE);
                        mBinding.handleBtn.setText("支付信息费");
                        mBinding.offerInfoBottomBar.setVisibility(View.VISIBLE);
                        mBinding.bottomPadding.setVisibility(View.GONE);
                        break;

                    case "3":
                        mBinding.messagePriceHint.setText("已支付信息费");
                        mBinding.handleBtn.setText("查看订单");
                        mBinding.lineView.setVisibility(View.VISIBLE);
                        mBinding.offerInfoBottomBar.setVisibility(View.VISIBLE);
                        mBinding.bottomPadding.setVisibility(View.GONE);
                        break;
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_btn:
                dissMiss();
                break;

            case R.id.handle_btn:
                clickHandleBtn();
                break;
        }
    }

    private void clickHandleBtn() {
        if (offerEntity != null && !TextUtils.isEmpty(offerEntity.getOfferStatus())) {
            if (offerEntity.getOfferStatus().equals("3")) {
                //查看订单
                if (!TextUtils.isEmpty(offerEntity.getOrderNo())) {
                    ActivityJump.jumpToActivity(mContext, TransportOrderDetailOwnerActivity.class, Pair.create("no", offerEntity.getOrderNo()),
                            Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                }else {
                    MToast.showToast(mContext,"未获取到订单号");
                }
            } else if (offerEntity.getOfferStatus().equals("2")) {
                payMessageSure(offerEntity);
            }
        }
    }

    /**
     * 支付信息费，确认接单
     *
     * @param entity
     */
    private void payMessageSure(OrderQuoteEntity entity) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setGoodsSourceNo(entity.getSourceNo());
        orderEntity.setCarNumber(entity.getCarNumber());
        orderEntity.setHeightHurdle(entity.getHeightHurdle());
        orderEntity.setWeight(entity.getWeight());
        orderEntity.setCarLen(entity.getCarLenName());
        orderEntity.setCarType(entity.getCarTypeName());
        orderEntity.setCityName(entity.getCityName());
        orderEntity.setProvinceName(entity.getProvinceName());
        orderEntity.setDistrictName(entity.getDistrictName());
        orderEntity.setDetailAddress(entity.getDetailAddress());
        orderEntity.setDriverNo(entity.getDriverNo());
        orderEntity.setCarOfferNo(entity.getCarOfferNo());
        orderEntity.setGoodsOfferNo(entity.getGoodsOfferNo());
        orderEntity.setNote(entity.getNote());
        orderEntity.setDiyField(entity.getDiyField());
        orderEntity.setQuotation(true);
        orderEntity.setIsDump(entity.getIsDump());
        orderEntity.setInTime(entity.getInTime());
        if (!UserOperating.getInstance().isPersonal()) {
            PayQuotationOrderForCompanyActivity.start(mContext, offerEntity.getGoodsOfferNo());
        } else {
            PayQuotationOrderActivity.start(mContext, offerEntity.getGoodsOfferNo());
        }
    }

    /**
     * 对字符加星号处理：除前面几位和后面几位外，其他的字符以星号代替
     *
     * @param content  传入的字符串
     * @param frontNum 保留前面字符的位数
     * @param endNum   保留后面字符的位数
     * @return 带星号的字符串
     */
    public static String replaceString2Star(String content, int frontNum, int endNum) {
        if (content == null || content.trim().isEmpty())
            return "";
        int len = content.length();

        if (frontNum >= len || frontNum < 0 || endNum >= len || endNum < 0)
            return content;

        if (frontNum + endNum >= len)
            return content;

        int beginIndex = frontNum;
        int endIndex = len - endNum;
        char[] cardChar = content.toCharArray();

        for (int j = beginIndex; j < endIndex; j++) {
            cardChar[j] = '*';
        }

        return new String(cardChar);
    }
}
